package service

import (
	"teacher-helper/dao"
	"teacher-helper/models"
	"teacher-helper/models/request"
)

func AddOneGrant(Grant models.SysGrant) error {
	return dao.DB.Create(&Grant).Error
}

func GetGrantList(queryInfo request.QueryInfo) (Grants []models.SysGrant, total int, err error) {
	if queryInfo == (request.QueryInfo{}){
		err = dao.DB.Find(&Grants).Count(&total).Error
		return
	}
	if queryInfo.Query == "" {
		if err = dao.DB.Model(&models.SysGrant{}).Count(&total).Error; err != nil {
			return
		}
		err = dao.DB.Limit(queryInfo.PageSize).Offset((queryInfo.PageNum - 1) * queryInfo.PageSize).Find(&Grants).Error
	} else {
		if err = dao.DB.Model(&models.SysGrant{}).Where("name like ?", queryInfo.Query+"%").Count(&total).Error; err != nil {
			return
		}
		err = dao.DB.Where("name like ?", queryInfo.Query+"%").Limit(queryInfo.PageSize).Offset((queryInfo.PageNum - 1) * queryInfo.PageSize).Find(&Grants).Error
	}
	return
}

func UpdateGrant(Grant models.SysGrant) error {
	return dao.DB.Save(&Grant).Error
}

func DeleteGrant(id int) error {
	return dao.DB.Where("id = ?", id).Delete(&models.SysGrant{}).Error
}

